﻿package com.cipri.battle.ui 
{
    import com.cipri.battle.events.BoxHitEvent;
	import flash.display.Sprite;
    import flash.events.MouseEvent;
	
	import com.cipri.battle.config.Settings;
	
	public class Box extends Sprite
	{
		private var _value:int;
		private var _color:uint;
		
		public function Box(val:int, color:int = -1) 
		{
			_value = val;
			
			if (color > -1) 
			{
                _color = color;
                drawBox();
			}
		}
        
        private function drawBox():void 
        {
            graphics.clear();
            graphics.lineStyle(Settings.BOX_OUTLINE_THICKNESS, Settings.BOX_OUTLINE_COLOR);
            graphics.beginFill(_color);
            graphics.drawRoundRect(0, 0, Settings.TABLE_CELL_SIZE, Settings.TABLE_CELL_SIZE, Settings.BOX_OUTLINE_ROUNDNESS);
            graphics.endFill();	
        }
        
        public function hit():void 
        {
            if (_value == 0) 
            {
                drawX();
            }
            else 
            {
                drawHit();
            }
        }
        
        public function startGame():void 
        {
            buttonMode = true;
            addEventListener(MouseEvent.CLICK, onClick);
            
            if (_value > 0) 
            {
                if (Settings["SHAPE_" + _value + "_BACKGROUND_COLOR"]) 
                {
                    _color = Settings["SHAPE_" + _value + "_BACKGROUND_COLOR"];
                }
                else 
                {
                    _color = Settings["SHAPE_BACKGROUND_COLOR"];
                }
                drawBox();
            }
        }
        
        private function onClick(event:MouseEvent):void 
        {
            hit();
            buttonMode = false;
            removeEventListener(MouseEvent.CLICK, onClick);
            var oldValue:uint = _value;
            _value = -1;
            dispatchEvent(new BoxHitEvent(BoxHitEvent.HIT, oldValue));
        }
        
        private function drawX():void 
        {
            var xShape:Sprite = new Sprite();
            xShape.graphics.lineStyle(Settings.BOX_X_THICKNESS, Settings.BOX_X_COLOR);
            xShape.graphics.moveTo(0, 0);
            xShape.graphics.lineTo(Settings.TABLE_CELL_SIZE, Settings.TABLE_CELL_SIZE);
            xShape.graphics.moveTo(Settings.TABLE_CELL_SIZE, 0);
            xShape.graphics.lineTo(0, Settings.TABLE_CELL_SIZE);
            addChild(xShape);
        }
        
        private function drawHit():void 
        {
            _color = Settings.BOX_X_HIT_COLOR;
            drawBox();
        }
		
		public function get value():int { return _value; }
        
        public function set value(value:int):void 
        {
            _value = value;
        }
	}
}